'use strict';

const { ACTION_TYPE } = require('../constants/actionType');

// 获取Controller类
const Controller = require('egg').Controller;

class UserController extends Controller {
  async register() {
    const { ctx } = this;
    const { email, username, password, verifyCode } = ctx.request.body;
    const success = await ctx.service.user.register(email, username, password, verifyCode);
    ctx.body = ctx.helper.formatResponse({ success }, 200, '注册成功');
  }

  async login() {
    const { ctx } = this;
    const { id, password } = ctx.request.body;
    console.log(ctx.request.body);
    const tokenInfo = await ctx.service.user.login(id, password);
    const token = ctx.helper.getToken(tokenInfo);
    ctx.body = ctx.helper.formatResponse({ token }, 200, '登录成功');
  }

  async modifyPassword() {
    const { ctx } = this;
    const { email, newPassword, verifyCode } = ctx.request.body;
    const { success, userId } = await ctx.service.user.modifyPassword(email, newPassword, verifyCode);
    await ctx.service.record.create(userId, ACTION_TYPE.ModifyPassword, '');
    ctx.body = ctx.helper.formatResponse({ success }, 200, '修改密码成功');
  }

  async modifyProfile() {
    const { ctx } = this;
    const { userId } = ctx.helper.jsonToHump(ctx.decode);
    const profileLink = await ctx.service.user.modifyProfile(userId);
    await ctx.service.record.create(userId, ACTION_TYPE.ModifyProfile, `头像url：${profileLink}`);
    ctx.body = ctx.helper.formatResponse({ profileLink }, 200, '更新头像成功');
  }

  async info() {
    const { ctx } = this;
    // 获取token用户信息
    const { userId } = ctx.helper.jsonToHump(ctx.decode);
    const info = await ctx.service.user.info(userId);
    ctx.body = ctx.helper.formatResponse(ctx.helper.jsonToHump(info), 200, '获取用户信息成功');
  }

  async statistic() {
    const { ctx } = this;
    const { userId } = ctx.helper.jsonToHump(ctx.decode);
    const statistic = await ctx.service.user.statistic(userId);
    ctx.body = ctx.helper.formatResponse(ctx.helper.jsonToHump(statistic), 200, '获取用户统计数据成功');
  }
}
module.exports = UserController;
